package com.toman.ui.work.workshop;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.PostRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.TimeEnum;
import com.toman.Enum.ViewTypeEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.BeltlineEntity;
import com.toman.JavaBean.DeviceHouseDayPlanMappingEntity;
import com.toman.R;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.bean.TemplateInfBean;
import com.toman.bean.TemplateInfBeanPreHandler;
import com.toman.camera.Camera;
import com.toman.templateActivity.controler.TempInfAdapter;
import com.toman.templateActivity.controler.TempView;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.callback.StringLoadingCallback;
import com.toman.widget.callback.http.AddCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 邹苏隆 on 2018/11/5.
 * description：
 */
public class NoplanReportAddActivity extends ToolBarActivity {
    @BindView(R.id.ll)
    LinearLayout ll;
    private TempInfAdapter adapter;
    List<TemplateInfBean> list = new ArrayList<>();
    Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_problem_feedback_inf);
        setContentView(R.layout.layout_template_inf);

        ButterKnife.bind(this);
        initView();
    }

    private void initView() {

        baseEnum=BaseEnum.NOPLANSUBMIT;
        initToolBar(baseEnum.add());

        TemplateInfBean depBean =new TemplateInfBean("departmentId", "部门名称", "", null, ViewTypeEnum.CLICK, NetworkEnum.DEP, mCompanyId, false, true,true);
        TemplateInfBean shiftBean =new TemplateInfBean("shiftId", "班次", "", null, ViewTypeEnum.CLICK, NetworkEnum.SHIFTANDTIME, mCompanyId, false, true,true){
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                Map<String, String> map = new HashMap<String, String>();
map.put("departmentId",observable.getResult());
                listener.setMap(map);
                adapter.refresh();
            }
        };
        shiftBean.getList_keys().add("isToday");
        shiftBean.getList_keys().add("endTime");


        depBean.getListeners().add(shiftBean);
        TemplateInfBean endBean =   new TemplateInfBean("endDate", "截止时间", "", null, ViewTypeEnum.DATE,TimeEnum.BOTH, false, true,true ){
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
//                通过班次判断是否隔天 带出截止时间
if (observable.getList_get().get(0)==null||observable.getList_get().get(0).equals("0")) {
    listener.setContent(TimeUtil.getNowTimeNew() + " " + observable.getList_get().get(1));
    listener.setResult(TimeUtil.getNowTimeNew() + " " + observable.getList_get().get(1));

}
else if (observable.getList_get().get(0).equals("1")){
    listener.setContent(TimeUtil.getNowTimeAddOneDay() + " " + observable.getList_get().get(1));
    listener.setResult(TimeUtil.getNowTimeAddOneDay() + " " + observable.getList_get().get(1));
}
                adapter.refresh();
            }

        };
        shiftBean.getListeners().add(endBean);

        TemplateInfBean productBean =new TemplateInfBean("productId", "品名", "", null, ViewTypeEnum.CLICK, NetworkEnum.PRODUCT, mCompanyId, true, true,false);
        productBean.getList_keys().add("productMode");
        TemplateInfBean typeBean =new TemplateInfBean(null, "型号", "", null, ViewTypeEnum.TEXT, NetworkEnum.PRODUCT, mCompanyId, false, false,false){
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable.getList_get().get(0)!=null) {
                    listener.setContent(observable.getList_get().get(0));
                }
                else {
                    listener.setContent("");
                }
                adapter.refresh();

            }
        };
        productBean.getListeners().add(typeBean);
productBean.getList_keys().add("artlineId");

        TemplateInfBean orderBean =new TemplateInfBean("orderId", "工序名称", "", null, ViewTypeEnum.CLICK, NetworkEnum.ORDER, mCompanyId, false, true,false){
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable==productBean){
                    Map<String, String> map = new HashMap<String, String>();
                    if (observable.getList_get().get(1)!=null)
                    map.put("artlineId",observable.getList_get().get(1));
                    listener.setMap(map);
                    adapter.refresh();
                }
            }
        };
        productBean.getListeners().add(orderBean);
        orderBean.getList_keys().add("beltlineEnties");
        TemplateInfBean beletBean = new TemplateInfBean("beltlineId", "产线名称", "", null, ViewTypeEnum.CLICK, NetworkEnum.BELTLINE, mCompanyId, false, true, true){
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {

                super.doAction(observable, listener);
                if (observable==depBean){
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("departmentId",observable.getResult());
                    listener.setMap(map);
                }
              else   if (observable==orderBean){
                    if (observable.getList_get().get(0)!=null){
                        List<BeltlineEntity> jsonArray = new ArrayList<>(JsonExcludeNull.parseArrayExcludeNull(observable.getList_get().get(0), BeltlineEntity.class));
                         List<ItemListBean> itemListBeans=new ArrayList<>();
                        for (BeltlineEntity entity : jsonArray) {
                            if (entity.getDepartmentId().equals(depBean.getResult())||StringUtils.isEmpty(depBean.getResult()))
                            {itemListBeans.add(new ItemListBean(entity.getBeltlineName(),entity.getId()+""));}
                        }

                        listener.setItemListBeans(itemListBeans);

                    }

                }
                adapter.refresh();
            }

        };
        TemplateInfBean manBean =new TemplateInfBean("opUserId", "操作工", "", null, ViewTypeEnum.CLICK, NetworkEnum.OPERATOR, mCompanyId, false, true,true){
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable==beletBean){
                Map<String, String> map = new HashMap<String, String>();
                if (observable.getResult()!=null)
                    map.put("beltlineId",observable.getResult());
                listener.setMap(map);
                adapter.refresh();
            }
        }
        };
        beletBean.getListeners().add(manBean);

        orderBean.getListeners().add(beletBean);
        depBean.getListeners().add(beletBean);
        depBean.getListeners().add(manBean);

        depBean.getPreHandlers().add(new TemplateInfBeanPreHandler() {
            @Override
            public boolean preHandle() {
                for (TemplateInfBean templateInfBean : depBean.getListeners()) {
                    templateInfBean.setResult(null);
                    templateInfBean.setContent(null);
                }
                beletBean.setResult(null);
                beletBean.setContent(null);
                adapter.refresh();
                return true;
            }
        });

        beletBean.getPreHandlers().add(new TemplateInfBeanPreHandler() {
            @Override
            public boolean preHandle() {
                for (TemplateInfBean templateInfBean : beletBean.getListeners()) {
                    templateInfBean.setResult(null);
                    templateInfBean.setContent(null);
                }
                adapter.refresh();
                return true;
            }
        });
        list.add(depBean);
        list.add(new TemplateInfBean("reportDate", "日期", "", null, ViewTypeEnum.DATE,TimeEnum.DATE, false, true,true ));
        list.add(shiftBean);
        list.add(endBean);
        list.add(productBean);
        list.add(typeBean);
        list.add(orderBean);
        list.add(beletBean);
        list.add(manBean);
        list.add(new TemplateInfBean("completedCount", "提交完工数", "", null, ViewTypeEnum.EDIT, InputType.TYPE_CLASS_NUMBER, false, true,true));
        list.add(new TemplateInfBean("qualifiedCount", "提交合格数", "", null, ViewTypeEnum.EDIT, InputType.TYPE_CLASS_NUMBER, false, true,true));
        list.add(new TemplateInfBean("addDesc", "备注", "", null, ViewTypeEnum.EDITMORE, true, true,false));
        list.add(new TemplateInfBean("remark", "产品图片或截图", "", null, ViewTypeEnum.PHOTO,null,this, true, true,false));

     //添加部门前置清理条件


        adapter = new TempInfAdapter(list, this, ll,true);


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera = list.get(12).getCamera();

        camera.onActivityResult(requestCode, resultCode, data);
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.toolbar_edit, menu);
//
//
//        MenuItem menuItem = menu.findItem(R.id.menu_edit);
////        还没配置权限
////        if (status.equals("3")|| !SPUtils.contains(getApplicationContext(), BaseEnum.FEEDBACK.has(PermEnum.EDIT))) {
////            menuItem.setVisible(false);
////        }
//        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                switch (item.getItemId()) {
//                    case R.id.menu_edit:
////                        if (item.getTitle().equals("编辑")) {
////                            item.setTitle("完成");
////                            adapter.edit(true);
////                            camera = list.get(6).getCamera();
////                        } else {
////                            item.setTitle("编辑");
////                            adapter.edit(false);
////                            camera = list.get(6).getCamera();
////
////                        }
//                        break;
//                }
//                return false;
//            }
//        });
//
//        return true;
//    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_finish);
//        还没配置权限
//        if (status.equals("3")|| !SPUtils.contains(getApplicationContext(), BaseEnum.FEEDBACK.has(PermEnum.EDIT))) {
//            menuItem.setVisible(false);
//        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
//                        if (item.getTitle().equals("编辑")) {
//                            item.setTitle("完成");
//                            adapter.edit(true);
//                            camera = list.get(6).getCamera();
//                        } else {
//                            item.setTitle("编辑");
//                            adapter.edit(false);
//                            camera = list.get(6).getCamera();
//
//                        }
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    public void add() {
        camera = list.get(12).getCamera();

        if (dialog != null) {
            dialog.dismiss();
        }
       if (adapter.isNull()){return;};
            if (TempView.compareString(this,list.get(9),list.get(10) )
                ) {
            return;
        }

        PostRequest request = OkHttpUtils
                .post(NewBaseUrl.devicehouse_noplanreport_save)
                .headers("User-Agent","Android")
                .headers("Content-Type", "multipart/form-data")
                .headers("token", this.token)
                .addFileParams("file",ViewUtil.getFiles(camera))
                ;

        for (TemplateInfBean bean :list){
            if (bean.getName()!=null&&bean.getType()!=ViewTypeEnum.PHOTO){
                request.params(bean.getName(),bean.getResult());
            }
        }
              request  .execute(new AddCallback(this) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", ": " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
//                            ToastUtil.makeText(getApplicationContext(),"获取wifi信号强度成功，状态约30s后会更新");
                            finish();


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


}
